<template>
    <!--Dialog-->
    <Dialog v-model="modelValue">
        <el-form :status-icon="true" :inline="true" :model="updateForm" label-width="auto" ref="updateFormRef">
            <el-row>
                <el-col :span="24">
                    <el-form-item label="名称" prop="name"
                        :rules="[{ required: true, message: '请输入名称' }, { min: 1, max: 30, message: '长度在 1 到 30 个字符' }]">
                        <el-input v-model="updateForm.name" placeholder="请输入名称" maxlength="256"
                            class="form-item-input" />
                    </el-form-item>
                    <el-form-item label="别名" prop="alias"
                        :rules="[{ required: true, message: '请输入别名' }, { min: 1, max: 30, message: '长度在 1 到 30 个字符' }]">
                        <el-input v-model="updateForm.alias" placeholder="请输入别名" maxlength="256"
                            class="form-item-input" />
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item label="类型" prop="key"
                        :rules="[{ required: true, message: '请输入类型' }, { min: 1, max: 30, message: '长度在 1 到 30 个字符' }]">
                        <el-input v-model="updateForm.key" placeholder="请输入类型" maxlength="256"
                            class="form-item-input" />
                    </el-form-item>
                    <el-form-item label="排序" prop="sort" :rules="[{ required: true, message: '请输入序号' }]">
                        <el-input type="number" v-model="updateForm.sort" placeholder="请输入序号" maxlength="256"
                            class="form-item-input" />
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item label="备注" prop="describe" class="form-item-remark"
                        :rules="[{ required: true, message: '请输入备注' }]">
                        <el-input :row="4" type="textarea" v-model="updateForm.describe" placeholder="请输入备注"
                            maxlength="1024" />
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        <template #footer>
            <el-button type="primary" @click="onSavue(updateFormRef)" :loading="isLoading">保存</el-button>
            <el-button @click="onClose">关闭</el-button>
        </template>
    </Dialog>
</template>

<script setup lang="ts">
import { Dialog } from '@/components/dialog/index';
import { propTypes } from '@/utils/propTypes';
import { onMounted, ref, } from 'vue';
import { ElMessage } from 'element-plus';
import { updateAsync, getAsync } from '@/utils/api/dict/category/index';
import type { FormInstance } from 'element-plus';
import type { DictCategoryDto, DictCategoryUpdateDto } from '@/utils/api/dict/category/type';
import type { ValidateFieldsError } from 'async-validator/dist-types';
import { Enable } from '@/utils/api/type';

// 定义参数
const props = defineProps({
    id: propTypes.string
});

// 定义emits
const emits = defineEmits<{
    (e: 'update:refresh'): void
}>();

// 刷新父组件
const refresh = () => {
    emits('update:refresh');
};

// 控制组件隐藏与显示
const modelValue = defineModel<boolean>(propTypes.bool.def(false));
const close = () => {
    modelValue.value = false;
};
// 保存Loading效果状态
const isLoading = ref<boolean>(false);

//组件挂载完毕
onMounted(async () => {
    const dict = await getAsync(props.id);
    updateForm.value = dict;
});

// 关闭
const onClose = () => {
    //触发自定义事件
    close();
};

// 保存
const onSavue = async (formEl: FormInstance | undefined): Promise<void> => {
    if (!formEl) {
        return;
    }
    // 提交验证
    await formEl.validate(
        async (isValid: boolean, invalidFields?: ValidateFieldsError): Promise<void> => {
            if (isValid) {
                try {
                    isLoading.value = true;

                    const dto = createDictCategoryUpdateDto(updateForm.value);
                    await updateAsync(updateForm.value.id, dto);

                    // 关闭弹窗
                    close();

                    // 提示成功
                    ElMessage({
                        showClose: true,
                        message: '修改成功',
                        type: 'success'
                    });

                    // 刷新父组件
                    refresh();

                } catch (error) {
                    if (error) {
                        let msg: string = (error as Error).message;
                        if (msg) {
                            ElMessage({
                                showClose: true,
                                message: (error as Error).message,
                                type: 'error'
                            });
                        }
                    }
                } finally {
                    isLoading.value = false;
                }
            } else {
                console.log('error submit!', invalidFields);
            }
        }
    );
};

// 组件实例
const updateFormRef = ref<FormInstance>();

// 添加对象
const updateForm = ref<DictCategoryDto>({
    name: '',
    key: '',
    alias: '',
    describe: '',
    sort: 0,
    concurrencyStamp: '',
    status: Enable.Enabled,
    id: '',
    code: ''
});

// 转换对象
const createDictCategoryUpdateDto = (dto: DictCategoryDto): DictCategoryUpdateDto => {
    return {
        name: dto.name,
        alias: dto.alias,
        describe: dto.describe,
        sort: dto.sort,
        concurrencyStamp: dto.concurrencyStamp,
        status: dto.status,
    };
};

</script>
<style scoped lang="scss">
.form-item-remark {
    width: calc(100% - 32px);
}

.form-item-input {
    width: 256px;
}
</style>